| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501 |
- import React, { useEffect } from 'react';
- import EventEmitter from 'events';
- import { isClient, pagePathUtils, pathUtils } from '@growi/core';
- import ExtensibleCustomError from 'extensible-custom-error';
- import {
- NextPage, GetServerSideProps, GetServerSidePropsContext,
- } from 'next';
- import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
- import dynamic from 'next/dynamic';
- import Head from 'next/head';
- import { useRouter } from 'next/router';
- import { PageAlerts } from '~/components/PageAlert/PageAlerts';
- // import { PageComments } from '~/components/PageComment/PageComments';
- // import { useTranslation } from '~/i18n';
- import { CrowiRequest } from '~/interfaces/crowi-request';
- // import { renderScriptTagByName, renderHighlightJsStyleTag } from '~/service/cdn-resources-loader';
- // import { useIndentSize } from '~/stores/editor';
- // import { useRendererSettings } from '~/stores/renderer';
- // import { EditorMode, useEditorMode, useIsMobile } from '~/stores/ui';
- import { CustomWindow } from '~/interfaces/global';
- import { IPageWithMeta } from '~/interfaces/page';
- import { GrowiRendererConfig, RendererSettings } from '~/interfaces/services/renderer';
- import { ISidebarConfig } from '~/interfaces/sidebar-config';
- import { PageModel, PageDocument } from '~/server/models/page';
- import UserUISettings, { UserUISettingsDocument } from '~/server/models/user-ui-settings';
- import Xss from '~/services/xss';
- import { useSWRxCurrentPage, useSWRxPageInfo, useSWRxPage } from '~/stores/page';
- import { useRendererSettings } from '~/stores/renderer';
- import {
- usePreferDrawerModeByUser, usePreferDrawerModeOnEditByUser, useSidebarCollapsed, useCurrentSidebarContents, useCurrentProductNavWidth,
- } from '~/stores/ui';
- import loggerFactory from '~/utils/logger';
- // import { isUserPage, isTrashPage, isSharedPage } from '~/utils/path-utils';
- // import GrowiSubNavigation from '../client/js/components/Navbar/GrowiSubNavigation';
- // import GrowiSubNavigationSwitcher from '../client/js/components/Navbar/GrowiSubNavigationSwitcher';
- import { BasicLayout } from '../components/BasicLayout';
- import DisplaySwitcher from '../components/Page/DisplaySwitcher';
- // import { serializeUserSecurely } from '../server/models/serializers/user-serializer';
- // import PageStatusAlert from '../client/js/components/PageStatusAlert';
- import {
- useCurrentUser, useCurrentPagePath,
- useOwnerOfCurrentPage, useIsLatestRevision,
- useIsForbidden, useIsNotFound, useIsTrashPage, useShared, useShareLinkId, useIsSharedUser, useIsAbleToDeleteCompletely,
- useAppTitle, useSiteUrl, useConfidential, useIsEnabledStaleNotification,
- useIsSearchServiceConfigured, useIsSearchServiceReachable, useIsMailerSetup,
- useAclEnabled, useIsAclEnabled, useHasSlackConfig, useDrawioUri, useHackmdUri,
- useNoCdn, useEditorConfig, useCsrfToken, useIsSearchScopeChildrenAsDefault, useCurrentPageId, useCurrentPathname, useIsSlackConfigured, useGrowiRendererConfig,
- } from '../stores/context';
- import { useXss } from '../stores/xss';
- import {
- CommonProps, getNextI18NextConfig, getServerSideCommonProps, useCustomTitle,
- } from './commons';
- // import { useCurrentPageSWR } from '../stores/page';
- const logger = loggerFactory('growi:pages:all');
- const { isPermalink: _isPermalink, isUsersHomePage, isTrashPage: _isTrashPage } = pagePathUtils;
- const { removeHeadingSlash } = pathUtils;
- const IdenticalPathPage = (): JSX.Element => {
- const IdenticalPathPage = dynamic(() => import('../components/IdenticalPathPage').then(mod => mod.IdenticalPathPage), { ssr: false });
- return <IdenticalPathPage />;
- };
- type Props = CommonProps & {
- currentUser: string,
- pageWithMetaStr: string,
- // pageUser?: any,
- // redirectTo?: string;
- // redirectFrom?: string;
- // shareLinkId?: string;
- isLatestRevision?: boolean
- isIdenticalPathPage?: boolean,
- isForbidden: boolean,
- isNotFound: boolean,
- // isAbleToDeleteCompletely: boolean,
- isSearchServiceConfigured: boolean,
- isSearchServiceReachable: boolean,
- isSearchScopeChildrenAsDefault: boolean,
- isSlackConfigured: boolean,
- // isMailerSetup: boolean,
- isAclEnabled: boolean,
- // hasSlackConfig: boolean,
- // drawioUri: string,
- // hackmdUri: string,
- // noCdn: string,
- // highlightJsStyle: string,
- // isAllReplyShown: boolean,
- // isContainerFluid: boolean,
- // editorConfig: any,
- isEnabledStaleNotification: boolean,
- // isEnabledLinebreaks: boolean,
- // isEnabledLinebreaksInComments: boolean,
- // adminPreferredIndentSize: number,
- // isIndentSizeForced: boolean,
- rendererSettings: RendererSettings,
- growiRendererConfig: GrowiRendererConfig,
- // UI
- userUISettings: UserUISettingsDocument | null
- // Sidebar
- sidebarConfig: ISidebarConfig,
- };
- const GrowiPage: NextPage<Props> = (props: Props) => {
- // const { t } = useTranslation();
- const router = useRouter();
- const UnsavedAlertDialog = dynamic(() => import('./UnsavedAlertDialog'), { ssr: false });
- const { data: currentUser } = useCurrentUser(props.currentUser != null ? JSON.parse(props.currentUser) : null);
- // register global EventEmitter
- if (isClient()) {
- (window as CustomWindow).globalEmitter = new EventEmitter();
- }
- // commons
- useAppTitle(props.appTitle);
- useSiteUrl(props.siteUrl);
- useXss(new Xss());
- // useEditorConfig(props.editorConfig);
- useConfidential(props.confidential);
- useCsrfToken(props.csrfToken);
- // UserUISettings
- usePreferDrawerModeByUser(props.userUISettings?.preferDrawerModeByUser ?? props.sidebarConfig.isSidebarDrawerMode);
- usePreferDrawerModeOnEditByUser(props.userUISettings?.preferDrawerModeOnEditByUser);
- useSidebarCollapsed(props.userUISettings?.isSidebarCollapsed ?? props.sidebarConfig.isSidebarClosedAtDockMode);
- useCurrentSidebarContents(props.userUISettings?.currentSidebarContents);
- useCurrentProductNavWidth(props.userUISettings?.currentProductNavWidth);
- // page
- useCurrentPagePath(props.currentPathname);
- useIsLatestRevision(props.isLatestRevision);
- // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
- useIsForbidden(props.isForbidden);
- useIsNotFound(props.isNotFound);
- // useIsTrashPage(_isTrashPage(props.currentPagePath));
- // useShared();
- // useShareLinkId(props.shareLinkId);
- // useIsAbleToDeleteCompletely(props.isAbleToDeleteCompletely);
- useIsSharedUser(false); // this page cann't be routed for '/share'
- useIsEnabledStaleNotification(props.isEnabledStaleNotification);
- useIsSearchServiceConfigured(props.isSearchServiceConfigured);
- useIsSearchServiceReachable(props.isSearchServiceReachable);
- useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
- useIsSlackConfigured(props.isSlackConfigured);
- // useIsMailerSetup(props.isMailerSetup);
- useIsAclEnabled(props.isAclEnabled);
- // useHasSlackConfig(props.hasSlackConfig);
- // useDrawioUri(props.drawioUri);
- // useHackmdUri(props.hackmdUri);
- // useNoCdn(props.noCdn);
- // useIndentSize(props.adminPreferredIndentSize);
- useRendererSettings(props.rendererSettings);
- useGrowiRendererConfig(props.growiRendererConfig);
- // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
- // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
- // const { data: editorMode } = useEditorMode();
- let pageWithMeta: IPageWithMeta | undefined;
- if (props.pageWithMetaStr != null) {
- pageWithMeta = JSON.parse(props.pageWithMetaStr) as IPageWithMeta;
- }
- useCurrentPageId(pageWithMeta?.data._id);
- useSWRxCurrentPage(undefined, pageWithMeta?.data); // store initial data
- // useSWRxPage(pageWithMeta?.data._id);
- useSWRxPageInfo(pageWithMeta?.data._id, undefined, pageWithMeta?.meta); // store initial data
- useIsTrashPage(_isTrashPage(pageWithMeta?.data.path ?? ''));
- useCurrentPagePath(pageWithMeta?.data.path);
- useCurrentPathname(props.currentPathname);
- // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
- useEffect(() => {
- if (isClient() && window.location.pathname !== props.currentPathname) {
- router.replace(props.currentPathname, undefined, { shallow: true });
- }
- }, [props.currentPathname, router]);
- const classNames: string[] = [];
- // switch (editorMode) {
- // case EditorMode.Editor:
- // classNames.push('on-edit', 'builtin-editor');
- // break;
- // case EditorMode.HackMD:
- // classNames.push('on-edit', 'hackmd');
- // break;
- // }
- // if (props.isContainerFluid) {
- // classNames.push('growi-layout-fluid');
- // }
- // if (page == null) {
- // classNames.push('not-found-page');
- // }
- return (
- <>
- <Head>
- {/*
- {renderScriptTagByName('drawio-viewer')}
- {renderScriptTagByName('mathjax')}
- {renderScriptTagByName('highlight-addons')}
- {renderHighlightJsStyleTag(props.highlightJsStyle)}
- */}
- </Head>
- {/* <BasicLayout title={useCustomTitle(props, t('GROWI'))} className={classNames.join(' ')}> */}
- <BasicLayout title={useCustomTitle(props, 'GROWI')} className={classNames.join(' ')}>
- <header className="py-0">
- {/* <GrowiSubNavigation /> */}
- GrowiSubNavigation
- </header>
- <div className="d-edit-none">
- {/* <GrowiSubNavigationSwitcher /> */}
- GrowiSubNavigationSwitcher
- </div>
- <div id="grw-subnav-sticky-trigger" className="sticky-top"></div>
- <div id="grw-fav-sticky-trigger" className="sticky-top"></div>
- <div id="main" className={`main ${isUsersHomePage(props.currentPathname) && 'user-page'}`}>
- <div className="row">
- <div className="col">
- <div id="content-main" className="content-main grw-container-convertible">
- { props.isIdenticalPathPage && <IdenticalPathPage /> }
- { !props.isIdenticalPathPage && (
- <>
- <PageAlerts />
- { props.isForbidden
- ? <>ForbiddenPage</>
- : <DisplaySwitcher />
- }
- <div id="page-editor-navbar-bottom-container" className="d-none d-edit-block"></div>
- {/* <PageStatusAlert /> */}
- PageStatusAlert
- </>
- ) }
- </div>
- </div>
- {/* <div className="col-xl-2 col-lg-3 d-none d-lg-block revision-toc-container">
- <div id="revision-toc" className="revision-toc mt-3 sps sps--abv" data-sps-offset="123">
- <div id="revision-toc-content" className="revision-toc-content"></div>
- </div>
- </div> */}
- </div>
- </div>
- <footer>
- {/* <PageComments /> */}
- PageComments
- </footer>
- <UnsavedAlertDialog />
- </BasicLayout>
- </>
- );
- };
- function getPageIdFromPathname(currentPathname: string): string | null {
- return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
- }
- class MultiplePagesHitsError extends ExtensibleCustomError {
- pagePath: string;
- constructor(pagePath: string) {
- super(`MultiplePagesHitsError occured by '${pagePath}'`);
- this.pagePath = pagePath;
- }
- }
- async function getPageData(context: GetServerSidePropsContext, props: Props): Promise<IPageWithMeta|null> {
- const req: CrowiRequest = context.req as CrowiRequest;
- const { crowi } = req;
- const { revisionId } = req.query;
- const Page = crowi.model('Page') as PageModel;
- const { pageService } = crowi;
- const { currentPathname } = props;
- const pageId = getPageIdFromPathname(currentPathname);
- const isPermalink = _isPermalink(currentPathname);
- const { user } = req;
- // check whether the specified page path hits to multiple pages
- if (!isPermalink) {
- const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
- if (count > 1) {
- throw new MultiplePagesHitsError(currentPathname);
- }
- }
- const result: IPageWithMeta = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
- const page = result?.data as unknown as PageDocument;
- // populate & check if the revision is latest
- if (page != null) {
- page.initLatestRevisionField(revisionId);
- await page.populateDataToShowRevision();
- props.isLatestRevision = page.isLatestRevision();
- }
- return result;
- }
- async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props, pageWithMeta: IPageWithMeta|null): Promise<void> {
- const req: CrowiRequest = context.req as CrowiRequest;
- const { crowi } = req;
- const Page = crowi.model('Page') as PageModel;
- const { currentPathname } = props;
- const pageId = getPageIdFromPathname(currentPathname);
- const isPermalink = _isPermalink(currentPathname);
- const page = pageWithMeta?.data;
- if (props.isIdenticalPathPage) {
- // TBD
- }
- else if (page == null) {
- props.isNotFound = true;
- // check the page is forbidden or just does not exist.
- const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
- props.isForbidden = count > 0;
- }
- else {
- // /62a88db47fed8b2d94f30000 ==> /path/to/page
- if (isPermalink && page.isEmpty) {
- props.currentPathname = page.path;
- }
- // /path/to/page ==> /62a88db47fed8b2d94f30000
- if (!isPermalink && !page.isEmpty) {
- const isToppage = pagePathUtils.isTopPage(props.currentPathname);
- if (!isToppage) {
- props.currentPathname = `/${page._id}`;
- }
- }
- }
- }
- // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
- // const req: CrowiRequest = context.req as CrowiRequest;
- // const { crowi } = req;
- // const UserModel = crowi.model('User');
- // if (isUserPage(props.currentPagePath)) {
- // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
- // if (user != null) {
- // props.pageUser = JSON.stringify(user.toObject());
- // }
- // }
- // }
- async function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): Promise<void> {
- const req: CrowiRequest = context.req as CrowiRequest;
- const { crowi } = req;
- const {
- appService, searchService, configManager, aclService, slackNotificationService, mailService,
- } = crowi;
- props.isSearchServiceConfigured = searchService.isConfigured;
- props.isSearchServiceReachable = searchService.isReachable;
- props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
- props.isSlackConfigured = crowi.slackIntegrationService.isSlackConfigured;
- // props.isMailerSetup = mailService.isMailerSetup;
- props.isAclEnabled = aclService.isAclEnabled();
- // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
- // props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
- // props.hackmdUri = configManager.getConfig('crowi', 'app:hackmdUri');
- // props.mathJax = configManager.getConfig('crowi', 'app:mathJax');
- // props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
- // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
- // props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
- // props.isContainerFluid = configManager.getConfig('crowi', 'customize:isContainerFluid');
- props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
- // props.isEnabledLinebreaks = configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks');
- // props.isEnabledLinebreaksInComments = configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments');
- // props.editorConfig = {
- // upload: {
- // image: crowi.fileUploadService.getIsUploadable(),
- // file: crowi.fileUploadService.getFileUploadEnabled(),
- // },
- // };
- // props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
- // props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
- props.rendererSettings = {
- isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
- isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
- adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
- isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
- };
- props.growiRendererConfig = {
- isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:xss:isEnabledPrevention'),
- attrWhiteList: crowi.xssService.getAttrWhiteList(),
- tagWhiteList: crowi.xssService.getTagWhiteList(),
- highlightJsStyleBorder: crowi.configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
- plantumlUri: process.env.PLANTUML_URI ?? null,
- blockdiagUri: process.env.BLOCKDIAG_URI ?? null,
- };
- props.sidebarConfig = {
- isSidebarDrawerMode: configManager.getConfig('crowi', 'customize:isSidebarDrawerMode'),
- isSidebarClosedAtDockMode: configManager.getConfig('crowi', 'customize:isSidebarClosedAtDockMode'),
- };
- }
- /**
- * for Server Side Translations
- * @param context
- * @param props
- * @param namespacesRequired
- */
- async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
- const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
- props._nextI18Next = nextI18NextConfig._nextI18Next;
- }
- export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
- const req: CrowiRequest = context.req as CrowiRequest;
- const { user } = req;
- const result = await getServerSideCommonProps(context);
- // check for presence
- // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
- if (!('props' in result)) {
- throw new Error('invalid getSSP result');
- }
- const props: Props = result.props as Props;
- let pageWithMeta;
- try {
- pageWithMeta = await getPageData(context, props);
- props.pageWithMetaStr = JSON.stringify(pageWithMeta);
- }
- catch (err) {
- if (err instanceof MultiplePagesHitsError) {
- props.isIdenticalPathPage = true;
- }
- else {
- throw err;
- }
- }
- injectRoutingInformation(context, props, pageWithMeta);
- injectServerConfigurations(context, props);
- injectNextI18NextConfigurations(context, props, ['translation']);
- if (user != null) {
- props.currentUser = JSON.stringify(user);
- }
- // UI
- const userUISettings = user == null ? null : await UserUISettings.findOne({ user: user._id }).exec();
- props.userUISettings = JSON.parse(JSON.stringify(userUISettings));
- return {
- props,
- };
- };
- export default GrowiPage;
|